#include <stdio.h>
#include "unistd.h"
#include "sys/time.h"
#include "pthread.h"
#include "stdlib.h"
void *num_sqr(void *arg)
{
    int *num = (int *)arg;
    
    int *result = malloc(sizeof(int));

    *result = (*num) * (*num);

    sleep(1);

    return result;
}

int main()
{
    int num[5] = {1, 2, 3, 4, 5};
    int sum = 0;
    struct timeval start, end;
    gettimeofday(&start, NULL);
    pthread_t tid[5];
    for (int i = 0; i < 5; i++)
    {
        // 创建线程
        pthread_create(&tid[i], NULL, num_sqr, (void *)&num[i]);
        // sum = sum + num_sqr(num[i]);
    }
    // 从每个线程中获取结果
    int *result;
    for (int i = 0; i < 5; i++)
    {
        pthread_join(tid[i], (void **)&result);
        sum = sum + *result;
        // printf("result = %d\n", *result);

    }
    printf("sum = %d\n", sum);
    gettimeofday(&end, NULL);
    printf("time = %ld\n", end.tv_sec - start.tv_sec);
    free(result);
    return 0;
}
